package com.intexh.quickandroid.module.chat.sprinkles;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class DbOpenHelper extends SQLiteOpenHelper {

    private DbOpenHelper(Context context) {
        super(context, Sprinkles.sInstance.dbName, null, Sprinkles.sInstance.versionCode);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        executeMigrations(db, 0, Sprinkles.sInstance.versionCode);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        executeMigrations(db, oldVersion, newVersion);
    }

    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
        db.execSQL("PRAGMA foreign_keys=ON;");
    }

    private void executeMigrations(SQLiteDatabase db, int oldVersion, int newVersion) {
        int size = Sprinkles.sInstance.mMigrations.size();
        for (int i = 0; i < size; i++) {
            Sprinkles.sInstance.mMigrations.get(i).execute(db);
        }
    }

    static SQLiteDatabase sInstance;

    public static synchronized SQLiteDatabase getInstance() {
        if (sInstance == null) {
            sInstance = new DbOpenHelper(Sprinkles.sInstance.mContext).getWritableDatabase();
        }
        return sInstance;
    }

}
